package cn.pugle.mianshi.thread1To10;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * <p> Created by tzp on 2017/9/6.
 */
@SuppressWarnings({"Duplicates", "AlibabaRemoveCommentedCode"})
public class PrintToTen5 implements Runnable {
    private int count = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            while (count <= MAX) {
                lock.lock();
                try {
                    if (count % 2 == 0) {
                        System.out.println(Thread.currentThread() + " " + count++);
                        condition.signal();
                        if (count <= MAX) {
                            condition.await();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            while (count <= MAX) {
                lock.lock();
                try {
                    if (count % 2 == 1) {
                        System.out.println(Thread.currentThread() + " " + count++);
                        condition.signal();
                        if (count <= MAX) {
                            condition.await();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen5().run();
    }
}
